/**
 * Avatar Configuration Data Models
 * Defines the structure and validation for virtual avatar system
 */

// Avatar configuration constants
export const AVATAR_OPTIONS = {
  // Face shape options
  FACE_SHAPES: [
    { id: 'oval', name: '椭圆脸', icon: '🥚' },
    { id: 'round', name: '圆脸', icon: '🌕' },
    { id: 'square', name: '方脸', icon: '⬜' },
    { id: 'heart', name: '心形脸', icon: '💖' },
    { id: 'long', name: '长脸', icon: '📏' },
    { id: 'diamond', name: '菱形脸', icon: '💎' }
  ],

  // Hairstyle options
  HAIRSTYLES: [
    { id: 'short_straight', name: '短直发', category: 'short', gender: 'all' },
    { id: 'short_curly', name: '短卷发', category: 'short', gender: 'all' },
    { id: 'bob_cut', name: '波波头', category: 'medium', gender: 'female' },
    { id: 'medium_wavy', name: '中长波浪', category: 'medium', gender: 'female' },
    { id: 'long_straight', name: '长直发', category: 'long', gender: 'female' },
    { id: 'long_curly', name: '长卷发', category: 'long', gender: 'female' },
    { id: 'buzz_cut', name: '寸头', category: 'short', gender: 'male' },
    { id: 'crew_cut', name: '平头', category: 'short', gender: 'male' },
    { id: 'side_part', name: '侧分', category: 'medium', gender: 'male' },
    { id: 'messy_hair', name: '凌乱发型', category: 'medium', gender: 'male' }
  ],

  // Hair color options
  HAIR_COLORS: [
    { id: 'black', name: '黑色', hex: '#2C1810' },
    { id: 'dark_brown', name: '深棕色', hex: '#4A3728' },
    { id: 'brown', name: '棕色', hex: '#8B4513' },
    { id: 'light_brown', name: '浅棕色', hex: '#CD853F' },
    { id: 'blonde', name: '金色', hex: '#F5DEB3' },
    { id: 'red', name: '红色', hex: '#B22222' },
    { id: 'gray', name: '灰色', hex: '#808080' }
  ],

  // Eye shape options
  EYE_SHAPES: [
    { id: 'almond', name: '杏仁眼', icon: '👁️' },
    { id: 'round', name: '圆眼', icon: '⭕' },
    { id: 'narrow', name: '细长眼', icon: '➖' },
    { id: 'wide', name: '大眼', icon: '👀' },
    { id: 'upturned', name: '上扬眼', icon: '↗️' },
    { id: 'downturned', name: '下垂眼', icon: '↘️' }
  ],

  // Clothing categories and options
  CLOTHING: {
    CASUAL: [
      { id: 'tshirt', name: 'T恤', colors: ['white', 'black', 'blue', 'red', 'green'] },
      { id: 'hoodie', name: '卫衣', colors: ['gray', 'black', 'navy', 'pink'] },
      { id: 'sweater', name: '毛衣', colors: ['beige', 'white', 'gray', 'burgundy'] },
      { id: 'polo', name: 'Polo衫', colors: ['white', 'navy', 'red', 'green'] }
    ],
    FORMAL: [
      { id: 'shirt', name: '衬衫', colors: ['white', 'light_blue', 'pink', 'gray'] },
      { id: 'blazer', name: '西装外套', colors: ['black', 'navy', 'gray', 'brown'] },
      { id: 'dress_shirt', name: '正装衬衫', colors: ['white', 'light_blue'] },
      { id: 'suit', name: '西装', colors: ['black', 'navy', 'charcoal'] }
    ],
    DRESS: [
      { id: 'casual_dress', name: '休闲连衣裙', colors: ['floral', 'solid', 'striped'] },
      { id: 'formal_dress', name: '正式连衣裙', colors: ['black', 'navy', 'burgundy'] },
      { id: 'summer_dress', name: '夏日连衣裙', colors: ['white', 'yellow', 'pink', 'blue'] }
    ]
  },

  // Accessory options
  ACCESSORIES: [
    { id: 'glasses', name: '眼镜', types: ['none', 'round', 'square', 'cat_eye', 'aviator'] },
    { id: 'hat', name: '帽子', types: ['none', 'cap', 'beanie', 'fedora', 'beret'] },
    { id: 'jewelry', name: '首饰', types: ['none', 'necklace', 'earrings', 'watch', 'bracelet'] },
    { id: 'scarf', name: '围巾', types: ['none', 'silk', 'wool', 'cotton'] }
  ]
};

// Default avatar configuration
export const DEFAULT_AVATAR_CONFIG = {
  faceShape: 'oval',
  hairstyle: 'short_straight',
  hairColor: 'black',
  eyeShape: 'almond',
  clothing: {
    category: 'casual',
    item: 'tshirt',
    color: 'white'
  },
  accessories: {
    glasses: 'none',
    hat: 'none',
    jewelry: 'none',
    scarf: 'none'
  },
  version: '1.0'
};

/**
 * Avatar Configuration Class
 * Handles avatar data structure and validation
 */
export class AvatarConfig {
  constructor(config = {}) {
    this.faceShape = config.faceShape || DEFAULT_AVATAR_CONFIG.faceShape;
    this.hairstyle = config.hairstyle || DEFAULT_AVATAR_CONFIG.hairstyle;
    this.hairColor = config.hairColor || DEFAULT_AVATAR_CONFIG.hairColor;
    this.eyeShape = config.eyeShape || DEFAULT_AVATAR_CONFIG.eyeShape;
    this.clothing = { ...DEFAULT_AVATAR_CONFIG.clothing, ...config.clothing };
    this.accessories = { ...DEFAULT_AVATAR_CONFIG.accessories, ...config.accessories };
    this.version = config.version || DEFAULT_AVATAR_CONFIG.version;
  }

  /**
   * Validate avatar configuration
   * @returns {Object} Validation result with isValid and errors
   */
  validate() {
    const errors = [];

    // Validate face shape
    if (!this.isValidFaceShape(this.faceShape)) {
      errors.push('Invalid face shape');
    }

    // Validate hairstyle
    if (!this.isValidHairstyle(this.hairstyle)) {
      errors.push('Invalid hairstyle');
    }

    // Validate hair color
    if (!this.isValidHairColor(this.hairColor)) {
      errors.push('Invalid hair color');
    }

    // Validate eye shape
    if (!this.isValidEyeShape(this.eyeShape)) {
      errors.push('Invalid eye shape');
    }

    // Validate clothing
    if (!this.isValidClothing(this.clothing)) {
      errors.push('Invalid clothing configuration');
    }

    // Validate accessories
    if (!this.isValidAccessories(this.accessories)) {
      errors.push('Invalid accessories configuration');
    }

    return {
      isValid: errors.length === 0,
      errors
    };
  }

  /**
   * Check if face shape is valid
   */
  isValidFaceShape(faceShape) {
    return AVATAR_OPTIONS.FACE_SHAPES.some(shape => shape.id === faceShape);
  }

  /**
   * Check if hairstyle is valid
   */
  isValidHairstyle(hairstyle) {
    return AVATAR_OPTIONS.HAIRSTYLES.some(style => style.id === hairstyle);
  }

  /**
   * Check if hair color is valid
   */
  isValidHairColor(hairColor) {
    return AVATAR_OPTIONS.HAIR_COLORS.some(color => color.id === hairColor);
  }

  /**
   * Check if eye shape is valid
   */
  isValidEyeShape(eyeShape) {
    return AVATAR_OPTIONS.EYE_SHAPES.some(shape => shape.id === eyeShape);
  }

  /**
   * Check if clothing configuration is valid
   */
  isValidClothing(clothing) {
    if (!clothing || typeof clothing !== 'object') return false;
    
    const { category, item, color } = clothing;
    
    // Check if category exists
    if (!AVATAR_OPTIONS.CLOTHING[category.toUpperCase()]) return false;
    
    // Check if item exists in category
    const categoryItems = AVATAR_OPTIONS.CLOTHING[category.toUpperCase()];
    const itemExists = categoryItems.some(clothingItem => clothingItem.id === item);
    
    if (!itemExists) return false;
    
    // Check if color is valid for the item
    const clothingItem = categoryItems.find(clothingItem => clothingItem.id === item);
    return clothingItem.colors.includes(color);
  }

  /**
   * Check if accessories configuration is valid
   */
  isValidAccessories(accessories) {
    if (!accessories || typeof accessories !== 'object') return false;
    
    for (const [accessoryType, accessoryValue] of Object.entries(accessories)) {
      const accessoryOption = AVATAR_OPTIONS.ACCESSORIES.find(acc => acc.id === accessoryType);
      if (!accessoryOption) return false;
      
      if (!accessoryOption.types.includes(accessoryValue)) return false;
    }
    
    return true;
  }

  /**
   * Get available hairstyles for gender
   */
  getHairstylesForGender(gender) {
    return AVATAR_OPTIONS.HAIRSTYLES.filter(style => 
      style.gender === 'all' || style.gender === gender
    );
  }

  /**
   * Get available clothing for category
   */
  getClothingForCategory(category) {
    return AVATAR_OPTIONS.CLOTHING[category.toUpperCase()] || [];
  }

  /**
   * Generate random avatar configuration
   */
  static generateRandom(gender = 'all') {
    const randomChoice = (array) => array[Math.floor(Math.random() * array.length)];
    
    // Filter hairstyles by gender
    const availableHairstyles = AVATAR_OPTIONS.HAIRSTYLES.filter(style => 
      style.gender === 'all' || style.gender === gender
    );
    
    // Choose random clothing category and item
    const clothingCategories = Object.keys(AVATAR_OPTIONS.CLOTHING);
    const randomCategory = randomChoice(clothingCategories).toLowerCase();
    const categoryItems = AVATAR_OPTIONS.CLOTHING[randomCategory.toUpperCase()];
    const randomItem = randomChoice(categoryItems);
    const randomColor = randomChoice(randomItem.colors);
    
    return new AvatarConfig({
      faceShape: randomChoice(AVATAR_OPTIONS.FACE_SHAPES).id,
      hairstyle: randomChoice(availableHairstyles).id,
      hairColor: randomChoice(AVATAR_OPTIONS.HAIR_COLORS).id,
      eyeShape: randomChoice(AVATAR_OPTIONS.EYE_SHAPES).id,
      clothing: {
        category: randomCategory,
        item: randomItem.id,
        color: randomColor
      },
      accessories: {
        glasses: randomChoice(AVATAR_OPTIONS.ACCESSORIES.find(acc => acc.id === 'glasses').types),
        hat: randomChoice(AVATAR_OPTIONS.ACCESSORIES.find(acc => acc.id === 'hat').types),
        jewelry: randomChoice(AVATAR_OPTIONS.ACCESSORIES.find(acc => acc.id === 'jewelry').types),
        scarf: randomChoice(AVATAR_OPTIONS.ACCESSORIES.find(acc => acc.id === 'scarf').types)
      }
    });
  }

  /**
   * Serialize avatar configuration to JSON
   */
  toJSON() {
    return {
      faceShape: this.faceShape,
      hairstyle: this.hairstyle,
      hairColor: this.hairColor,
      eyeShape: this.eyeShape,
      clothing: this.clothing,
      accessories: this.accessories,
      version: this.version
    };
  }

  /**
   * Create avatar configuration from JSON
   */
  static fromJSON(jsonData) {
    try {
      const config = typeof jsonData === 'string' ? JSON.parse(jsonData) : jsonData;
      return new AvatarConfig(config);
    } catch (error) {
      console.error('Failed to parse avatar configuration:', error);
      return new AvatarConfig(); // Return default configuration
    }
  }

  /**
   * Clone avatar configuration
   */
  clone() {
    return new AvatarConfig(this.toJSON());
  }

  /**
   * Update specific avatar property
   */
  updateProperty(property, value) {
    const newConfig = this.clone();
    
    if (property.includes('.')) {
      // Handle nested properties like 'clothing.color'
      const [parent, child] = property.split('.');
      if (newConfig[parent] && typeof newConfig[parent] === 'object') {
        newConfig[parent][child] = value;
      }
    } else {
      newConfig[property] = value;
    }
    
    return newConfig;
  }

  /**
   * Get human-readable description of avatar
   */
  getDescription() {
    const faceShape = AVATAR_OPTIONS.FACE_SHAPES.find(shape => shape.id === this.faceShape)?.name || this.faceShape;
    const hairstyle = AVATAR_OPTIONS.HAIRSTYLES.find(style => style.id === this.hairstyle)?.name || this.hairstyle;
    const hairColor = AVATAR_OPTIONS.HAIR_COLORS.find(color => color.id === this.hairColor)?.name || this.hairColor;
    const eyeShape = AVATAR_OPTIONS.EYE_SHAPES.find(shape => shape.id === this.eyeShape)?.name || this.eyeShape;
    
    return `${faceShape}，${hairColor}${hairstyle}，${eyeShape}`;
  }
}